//
// Created by Senhai Xu on 2025/3/5.
//
//给定一个单链表的头结点pHead(该头节点是有值的，比如在下图，它的val是1)，长度为n，反转该链表后，返回新链表的表头。

#include <iostream>
 struct ListNode {
  int val;
  struct ListNode *next;
  ListNode(int x) : val(x), next(nullptr) {}
 };

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @return ListNode类
     * 1->2->3->4->5
     */
    ListNode* ReverseList(ListNode* head) {
//        边界
//        if(head == nullptr || head->next == nullptr) return head;
//        ListNode* pre = nullptr;
//        ListNode* curr = head;
//        ListNode* next;
//        while(curr != nullptr){
//            next = curr->next;
//            curr->next = pre;
//            pre = curr;
//            curr = next;
//        }

//        if(head == nullptr || head->next == nullptr) return head;
//        ListNode* ans = ReverseList(head->next);
//        head->next->next = head;
//        head->next = nullptr;
//        return ans;


    }

};

// 辅助函数：打印链表
void printList(ListNode* head) {
    ListNode* curr = head;
    while (curr != nullptr) {
        std::cout << curr->val << " ";
        curr = curr->next;
    }
    std::cout << std::endl;
}
int main() {
    // 创建一个示例链表: 1 -> 2 -> 3 -> 4 -> 5
    ListNode* head = new ListNode(1);
    head->next = new ListNode(2);
    head->next->next = new ListNode(3);
    head->next->next->next = new ListNode(4);
    head->next->next->next->next = new ListNode(5);
    Solution solution;

    std::cout << "Original list: ";
    printList(head);

    // 反转链表
    ListNode* reversedHead = solution.ReverseList(head);

    std::cout << "Reversed list: ";
    printList(reversedHead);

    // 释放链表内存
    while (reversedHead != nullptr) {
        ListNode* temp = reversedHead;
        reversedHead = reversedHead->next;
        delete temp;
    }

    return 0;
}